<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    
    <title>Java技术栈</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="分享Java后端技术干货，包括最新Java核心技术，高并发&amp;多线程编程，分布式&amp;微服务，架构设计，Java高级面试题，数据结构及算法，人工智能&amp;区块链应用，最新行业动态等。">
<meta name="keywords" content="Java技术, Spring Boot, Spring Cloud">
<meta property="og:type" content="website">
<meta property="og:title" content="Java技术栈">
<meta property="og:url" content="http://youanyyou.gitee.io/javastack/page/3/index.html">
<meta property="og:site_name" content="Java技术栈">
<meta property="og:description" content="分享Java后端技术干货，包括最新Java核心技术，高并发&amp;多线程编程，分布式&amp;微服务，架构设计，Java高级面试题，数据结构及算法，人工智能&amp;区块链应用，最新行业动态等。">
<meta property="og:locale" content="zh-CN">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java技术栈">
<meta name="twitter:description" content="分享Java后端技术干货，包括最新Java核心技术，高并发&amp;多线程编程，分布式&amp;微服务，架构设计，Java高级面试题，数据结构及算法，人工智能&amp;区块链应用，最新行业动态等。">
    

    
        <link rel="alternate" href="/" title="Java技术栈" type="application/atom+xml" />
    

    

    <link rel="stylesheet" href="/javastack/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/javastack/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/javastack/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/javastack/css/style.css">

    <script src="/javastack/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/javastack/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/javastack/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/javastack/" id="logo">
                <i class="logo"></i>
                <span class="site-title">Java技术栈</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/javastack/.">首页</a>
                
                    <a class="main-nav-link" href="/javastack/archives">归档</a>
                
                    <a class="main-nav-link" href="/javastack/categories">分类</a>
                
                    <a class="main-nav-link" href="/javastack/tags">标签</a>
                
                    <a class="main-nav-link" href="/javastack/about">关于</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/javastack/css/images/avatar.jpg" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/javastack/',
        CONTENT_URL: '/javastack/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/javastack/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td><a class="main-nav-link" href="/javastack/.">首页</a></td>
                
                    <td><a class="main-nav-link" href="/javastack/archives">归档</a></td>
                
                    <td><a class="main-nav-link" href="/javastack/categories">分类</a></td>
                
                    <td><a class="main-nav-link" href="/javastack/tags">标签</a></td>
                
                    <td><a class="main-nav-link" href="/javastack/about">关于</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/javastack/css/images/avatar.jpg" />
            <h2 id="name">Java技术栈</h2><br/>
            <h3 id="title">微信公众号,每日更新！</h3>
            <!--
            <span id="location">
                <i class="fa fa-map-marker"></i>Shenzhen, China
            </span>
            -->
            <a id="follow" target="_blank" href="http://youanyyou.gitee.io/javastack/css/images/avatar.jpg">扫描关注微信公众号</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                113
                <span>文章</span>
            </div>
            <div class="article-info-block">
                58
                <span>标签</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/ppoffice/hexo-theme-icarus" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/javastack/" target="_blank" title="twitter" class=tooltip>
                            <i class="fa fa-twitter"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/javastack/" target="_blank" title="facebook" class=tooltip>
                            <i class="fa fa-facebook"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/javastack/" target="_blank" title="dribbble" class=tooltip>
                            <i class="fa fa-dribbble"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/javastack/" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main">
    <article id="post-Spring Boot/Spring Boot 配置文件（bootstrap &amp; application）的区别和应用场景" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>用过 Spring Boot 的都知道在 Spring Boot 中有以下两种配置文件</p>
<ul>
<li>bootstrap (.yml 或者 .properties)</li>
<li>application (.yml 或者 .properties)</li>
</ul>
<p>为什么会有这两种配置文件呢？大家都清楚它们的区别和具体使用场景吗？</p>
<h4 id="bootstrap-application-的区别"><a href="#bootstrap-application-的区别" class="headerlink" title="bootstrap/ application 的区别"></a>bootstrap/ application 的区别</h4><p>特意去翻了下 Spring Boot 的官方文档，没有找到关于这两种文件的具体定义，然后再翻了下 Spring Cloud 的官方文档找到了它们的区别。</p>
<blockquote>
<p><a href="http://cloud.spring.io/spring-cloud-static/Edgware.SR3/single/spring-cloud.html#_the_bootstrap_application_context" target="_blank" rel="noopener">http://cloud.spring.io/spring-cloud-static/Edgware.SR3/single/spring-cloud.html#_the_bootstrap_application_context</a> </p>
</blockquote>
<p>认真阅读了下文档，原文大概意思是这样。</p>
<blockquote>
<p>Spring Cloud 构建于 Spring Boot 之上，在 Spring Boot 中有两种上下文，一种是 bootstrap, 另外一种是 application, bootstrap 是应用程序的父上下文，也就是说 bootstrap 加载优先于 applicaton。bootstrap 主要用于从额外的资源来加载配置信息，还可以在本地外部配置文件中解密属性。这两个上下文共用一个环境，它是任何Spring应用程序的外部属性的来源。bootstrap 里面的属性会优先加载，它们默认也不能被本地相同配置覆盖。</p>
</blockquote>
<p><strong>因此，对比 application 配置文件，bootstrap 配置文件具有以下几个特性。</strong></p>
<ul>
<li>boostrap 由父 ApplicationContext 加载，比 applicaton 优先加载</li>
<li>boostrap 里面的属性不能被覆盖</li>
</ul>
<h4 id="bootstrap-application-的应用场景"><a href="#bootstrap-application-的应用场景" class="headerlink" title="bootstrap/ application 的应用场景"></a>bootstrap/ application 的应用场景</h4><p>application 配置文件这个容易理解，主要用于 Spring Boot 项目的自动化配置。</p>
<p>bootstrap 配置文件有以下几个应用场景。</p>
<ul>
<li>使用 Spring Cloud Config 配置中心时，这时需要在 bootstrap 配置文件中添加连接到配置中心的配置属性来加载外部配置中心的配置信息；</li>
<li>一些固定的不能被覆盖的属性</li>
<li>一些加密/解密的场景；</li>
</ul>
<p>以下这个截图是一个国外网友问了一个 Spring Cloud 工程师得到的回答。</p>
<p><img src="http://p179cyr45.bkt.clouddn.com/18-4-2/38651438.jpg" alt=""></p>
<p>做过 Spring Cloud 微服务的朋友应该对 bootstrap 的应用十分清楚，我们也有 Spring Cloud 的实战教程，在 Spring 专题中都能看到。</p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://youanyyou.gitee.io/javastack/2018/04/18/Spring Boot/Spring Boot 配置文件（bootstrap & application）的区别和应用场景/" data-id="cjg4zd8nn003lhg8a1bk7b3y1" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    

        </footer>
    </div>
    
</article>



    <article id="post-Spring Boot/Spring Boot配置随机数" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>Spring Boot支持在系统加载的时候配置随机数。</p>
<p>添加config/random.properties文件，添加以下内容：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">#随机32位MD5字符串</span><br><span class="line">user.random.secret=$&#123;random.value&#125;</span><br><span class="line"></span><br><span class="line">#随机int数字</span><br><span class="line">user.random.intNumber=$&#123;random.int&#125;</span><br><span class="line"></span><br><span class="line">#随机long数字</span><br><span class="line">user.random.longNumber=$&#123;random.long&#125;</span><br><span class="line"></span><br><span class="line">#随便uuid</span><br><span class="line">user.random.uuid=$&#123;random.uuid&#125;</span><br><span class="line"></span><br><span class="line">#随机10以内的数字</span><br><span class="line">user.random.lessTen=$&#123;random.int(10)&#125;</span><br><span class="line"></span><br><span class="line">#随机1024~65536之内的数字</span><br><span class="line">user.random.range=$&#123;random.int[1024,65536]&#125;</span><br></pre></td></tr></table></figure>
<p>添加绑定类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line">import org.springframework.boot.context.properties.ConfigurationProperties;</span><br><span class="line">import org.springframework.context.annotation.PropertySource;</span><br><span class="line">import org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line">@Component</span><br><span class="line">@ConfigurationProperties(prefix = &quot;user.random&quot;)</span><br><span class="line">@PropertySource(value = &#123; &quot;config/random.properties&quot; &#125;)</span><br><span class="line">public class RandomConfig &#123;</span><br><span class="line"></span><br><span class="line">	private String secret;</span><br><span class="line">	private int intNumber;</span><br><span class="line">	private int lessTen;</span><br><span class="line">	private int range;</span><br><span class="line">	private long longNumber;</span><br><span class="line">	private String uuid;</span><br><span class="line"></span><br><span class="line">	public String getSecret() &#123;</span><br><span class="line">		return secret;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public void setSecret(String secret) &#123;</span><br><span class="line">		this.secret = secret;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public int getIntNumber() &#123;</span><br><span class="line">		return intNumber;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public void setIntNumber(int intNumber) &#123;</span><br><span class="line">		this.intNumber = intNumber;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public int getLessTen() &#123;</span><br><span class="line">		return lessTen;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public void setLessTen(int lessTen) &#123;</span><br><span class="line">		this.lessTen = lessTen;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public int getRange() &#123;</span><br><span class="line">		return range;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public void setRange(int range) &#123;</span><br><span class="line">		this.range = range;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public long getLongNumber() &#123;</span><br><span class="line">		return longNumber;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public void setLongNumber(long longNumber) &#123;</span><br><span class="line">		this.longNumber = longNumber;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public String getUuid() &#123;</span><br><span class="line">		return uuid;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public void setUuid(String uuid) &#123;</span><br><span class="line">		this.uuid = uuid;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>输出如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">secret=83a5c3402ef936a37842dc6de3d1af0f</span><br><span class="line">intNumber=1816149855</span><br><span class="line">lessTen=1</span><br><span class="line">range=37625</span><br><span class="line">longNumber=8449008776720010146</span><br><span class="line">uuid=e5bc2091-1599-45b1-abd7-e3721ac77e6b</span><br></pre></td></tr></table></figure>
<p>具体的生成细节可以参考Spring Boot的配置类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">org.springframework.boot.context.config.RandomValuePropertySource</span><br></pre></td></tr></table></figure>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://youanyyou.gitee.io/javastack/2018/04/18/Spring Boot/Spring Boot配置随机数/" data-id="cjg4zd8oj004chg8aae2jsi4w" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    

        </footer>
    </div>
    
</article>



    <article id="post-Spring Cloud/SpringCloud服务安全连接" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>Spring Cloud可以增加HTTP Basic认证来增加服务连接的安全性。</p>
<h2 id="1、加入security启动器"><a href="#1、加入security启动器" class="headerlink" title="1、加入security启动器"></a>1、加入security启动器</h2><p>在maven配置文件中加入Spring Boot的security启动器。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">	&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">	&lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<p>这样，就开启对服务连接的安全保护，系统默认为生成一个用户名为”user”及一个随机密码，随机密码在服务启动的时候在日志中会打印出来。</p>
<h2 id="2、自定义用户名密码"><a href="#2、自定义用户名密码" class="headerlink" title="2、自定义用户名密码"></a>2、自定义用户名密码</h2><p>随机密码没什么实际意义，我们需要一个固定的连接用户名和密码。</p>
<p>在应用配置文件中加入以下配置即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">security: </span><br><span class="line">  user: </span><br><span class="line">    name: admin</span><br><span class="line">    password: admin123456</span><br></pre></td></tr></table></figure>
<p>这样配置完后在连接这个服务的时候就会要求输入用户名和密码，如果认证失败会返回401错误。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    &quot;timestamp&quot;: 1502689874556,</span><br><span class="line">    &quot;status&quot;: 401,</span><br><span class="line">    &quot;error&quot;: &quot;Unauthorized&quot;,</span><br><span class="line">    &quot;message&quot;: &quot;Bad credentials&quot;,</span><br><span class="line">    &quot;path&quot;: &quot;/test/save&quot;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3、安全连接"><a href="#3、安全连接" class="headerlink" title="3、安全连接"></a>3、安全连接</h2><p>1、注册中心安全连接</p>
<p>username:password@ipaddress</p>
<p>2、Feign申明式服务安全连接</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@FeignClient(name = &quot;SERVICE&quot;, configuration = FeignAuthConfig.class)</span><br><span class="line">public interface OrderService extends OrderAPI &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">public class FeignAuthConfig &#123;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() &#123;</span><br><span class="line">    	return new BasicAuthRequestInterceptor(&quot;admin&quot;,&quot;admin123456&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://youanyyou.gitee.io/javastack/2018/04/18/Spring Cloud/SpringCloud服务安全连接/" data-id="cjg4zd8p3004shg8a11el9xdq" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    

        </footer>
    </div>
    
</article>



    <article id="post-Spring Cloud/Spring Cloud 多版本管理那些事。" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>好久没有研究 Spring Cloud 了，也没有关注它的更新及新特性，上官网看了下，又增加了几个版本，有正式版有预览版，多达 6 个版本，实在让人蒙逼。</p>
<p>而我们的项目版本还仪停留在 Dalston SR1 版本。</p>
<h4 id="Spring-Cloud-的多版本"><a href="#Spring-Cloud-的多版本" class="headerlink" title="Spring Cloud 的多版本"></a>Spring Cloud 的多版本</h4><p><img src="http://p179cyr45.bkt.clouddn.com/18-4-2/44559010.jpg" alt=""></p>
<p>这么多不同的版本，它们都有什么区别，我们开发微服务到底使用哪一个版本呢？这些版本与 Spring Boot 版本又是一个怎样的依赖关系？带着这些问题，我们必须把它一一搞清楚，不然总会让你很头疼。。</p>
<p>首先 Spring Cloud 是一个由很多子项目组成的庞大项目，Spring Cloud 的主要项目如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">Spring Cloud Config</span><br><span class="line">Spring Cloud Netflix</span><br><span class="line">Spring Cloud Bus</span><br><span class="line">Spring Cloud Cluster</span><br><span class="line">Spring Cloud Security</span><br><span class="line">...</span><br><span class="line"></span><br><span class="line">更多请参考官方说明：</span><br><span class="line">https://projects.spring.io/spring-cloud/</span><br></pre></td></tr></table></figure>
<p>然而，这些子项目都有不同的发布阶段，为了管理主项目和子项目的依赖关系，以及为了避免和子项目版本的冲突和误解，主项目版本命名并没有采用和子项目数字版本化的形式，而是采用了英文名称。</p>
<p>英文命名方式也比较有意思，Spring Cloud 采用了英国伦敦地铁站的名称来命名，并由地铁站名称字母A-Z依次类推的形式来发布迭代版本。</p>
<p>由上可知，Spring Cloud 的第一个版本 “Angel” 就不觉得奇怪了，接着 “Brixton” 就是第二个版本。当一个项目到达发布临界点或者解决了一个严重的BUG后就会发布一个 “service Release” 版本， 简称 SR（X）版本，x 代表一个递增数字。</p>
<p><strong>由此我们可以得出 “Finchley M9” 就是目前最新的开发版本，”Edgware SR3” 是最新稳定版本。</strong></p>
<h4 id="Spring-Cloud-版本依赖关系"><a href="#Spring-Cloud-版本依赖关系" class="headerlink" title="Spring Cloud 版本依赖关系"></a>Spring Cloud 版本依赖关系</h4><p>下图揭示了主项目和子项目版本的依赖关系。</p>
<p><img src="http://p179cyr45.bkt.clouddn.com/18-4-2/50615593.jpg" alt=""></p>
<h4 id="Spring-Cloud-amp-Spring-Boot-依赖关系"><a href="#Spring-Cloud-amp-Spring-Boot-依赖关系" class="headerlink" title="Spring Cloud &amp; Spring Boot 依赖关系"></a>Spring Cloud &amp; Spring Boot 依赖关系</h4><p><img src="http://p179cyr45.bkt.clouddn.com/18-4-2/47489606.jpg" alt=""></p>
<ul>
<li>Finchley 是基于 Spring Boot 2.0.x 构建的，不支持 Spring Boot 1.5.x</li>
<li>Dalston 和 Edgware 是基于 Spring Boot 1.5.x 构建的，不支持 Spring Boot 2.0.x</li>
<li>Camden 构建于 Spring Boot 1.4.x，但依然能支持 Spring Boot 1.5.x</li>
</ul>
<p>注意：Brixton 和 Angel 版本在2017年7月已经停止更新迭代了，我们就不关注它的版本依赖关系了。</p>
<p>Spring Cloud 正处理高速发展期，版本发布更新太快，项目更新版本还要考虑兼容性等各种问题，让人很头疼！后续我会慢慢揭开这些面纱。。</p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://youanyyou.gitee.io/javastack/2018/04/18/Spring Cloud/Spring Cloud 多版本管理那些事。/" data-id="cjg4zd8oz004phg8a0vue98bo" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    

        </footer>
    </div>
    
</article>



    <article id="post-Spring Cloud/Spring Cloud是什么？" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>Spring Cloud是一系列框架的有序集合。它利用Spring Boot的开发便利性巧妙地简化了分布式系统基础设施的开发，如服务发现注册、配置中心、消息总线、负载均衡、断路器、数据监控等，都可以用Spring Boot的开发风格做到一键启动和部署。</p>
<p>Spring并没有重复制造轮子，它只是将目前各家公司开发的比较成熟、经得起实际考验的服务框架组合起来，通过Spring Boot风格进行再封装屏蔽掉了复杂的配置和实现原理，最终给开发者留出了一套简单易懂、易部署和易维护的分布式系统开发工具包。</p>
<p>目前最新版本：Dalston.SR3</p>
<blockquote>
<p>官网：<a href="http://projects.spring.io/spring-cloud/" target="_blank" rel="noopener">http://projects.spring.io/spring-cloud/</a></p>
</blockquote>
<h2 id="特性"><a href="#特性" class="headerlink" title="特性"></a>特性</h2><p>Spring Cloud专注于提供良好的开箱即用经验的典型用例和可扩展性机制覆盖。</p>
<ul>
<li><p>分布式/版本化配置</p>
</li>
<li><p>服务注册和发现</p>
</li>
<li><p>路由</p>
</li>
<li><p>service - to - service调用</p>
</li>
<li><p>负载均衡</p>
</li>
<li><p>断路器</p>
</li>
<li><p>分布式消息传递</p>
</li>
</ul>
<h2 id="子项目"><a href="#子项目" class="headerlink" title="子项目"></a>子项目</h2><p>Spring Cloud的子项目，大致可分成两类，一类是对现有成熟框架”Spring Boot化”的封装和抽象，也是数量最多的项目；第二类是开发了一部分分布式系统的基础设施的实现，如Spring Cloud Stream扮演的就是kafka, ActiveMQ这样的角色。对于我们想快速实践微服务的开发者来说，第一类子项目就已经足够使用，如：</p>
<ul>
<li><p>Spring Cloud Netflix</p>
<p>  是对Netflix开发的一套分布式服务框架的封装，包括服务的发现和注册，负载均衡、断路器、REST客户端、请求路由等。
　　</p>
</li>
<li><p>Spring Cloud Config</p>
<p>  将配置信息外部化存储, 并能配合Spring Cloud Bus可以实现动态修改配置文件。
　　</p>
</li>
<li><p>Spring Cloud Bus</p>
<p>  分布式消息队列，是对Kafka, MQ的封装。
　　</p>
</li>
<li><p>Spring Cloud Security</p>
<p>  是对Spring Security的封装，能实现服务之间的认证调用和安全保护等，并能配合Netflix使用。
　　</p>
</li>
<li><p>Spring Cloud Zookeeper</p>
<p>  对Zookeeper的封装，使之能配置其它Spring Cloud的子项目使用。
　　</p>
</li>
<li><p>Spring Cloud Eureka</p>
<p>  是 Spring Cloud Netflix微服务套件中的一部分，它基于Netflix Eureka 做了二次分装，主要负责完成微服务架构中的服务治理功能。</p>
</li>
</ul>
<h2 id="前景"><a href="#前景" class="headerlink" title="前景"></a>前景</h2><p>Spring Cloud对于中小型互联网公司来说是一种福音，因为这类公司往往没有实力或者没有足够的资金投入去开发自己的分布式系统基础设施，使用Spring Cloud一站式解决方案能在从容应对业务发展的同时大大减少开发成本。同时，随着近几年微服务架构和Docker容器概念的火爆，也会让Spring Cloud在未来越来越“云”化的软件开发风格中立有一席之地，尤其是在目前五花八门的分布式解决方案中提供了标准化的、全站式的技术方案，意义可能会堪比当前Servlet规范的诞生，有效推进服务端软件系统技术水平的进步。</p>
<h2 id="和dubbo的对比"><a href="#和dubbo的对比" class="headerlink" title="和dubbo的对比"></a>和dubbo的对比</h2><table>
<thead>
<tr>
<th>组件</th>
<th>Dubbo</th>
<th>Spring Cloud</th>
</tr>
</thead>
<tbody>
<tr>
<td>服务注册中心</td>
<td>Zookeeper</td>
<td>Spring Cloud Netflix Eureka</td>
</tr>
<tr>
<td>服务调用方式</td>
<td>RPC</td>
<td>REST API</td>
</tr>
<tr>
<td>服务网关</td>
<td>无</td>
<td>Spring Cloud Netflix Zuul</td>
</tr>
<tr>
<td>断路器</td>
<td>不完善</td>
<td>Spring Cloud Netflix Hystrix</td>
</tr>
<tr>
<td>分布式配置</td>
<td>无</td>
<td>Spring Cloud Config</td>
</tr>
<tr>
<td>服务跟踪</td>
<td>无</td>
<td>Spring Cloud Sleuth</td>
</tr>
<tr>
<td>消息总线</td>
<td>无</td>
<td>Spring Cloud Bus</td>
</tr>
<tr>
<td>数据流</td>
<td>无</td>
<td>Spring Cloud Stream</td>
</tr>
<tr>
<td>批量任务</td>
<td>无</td>
<td>Spring Cloud Task</td>
</tr>
<tr>
<td>…</td>
<td>…</td>
<td>…</td>
</tr>
</tbody>
</table>
<p>所以，对比看出其实没什么比较性，Dubbo只是Spring Cloud的一个子集而已，Spring Cloud是一系列的分布式的解决方案包。不过随着目前Dubbo官方的重新申明维护并得到重视，Dubbo生态圈也会逐渐强大。</p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://youanyyou.gitee.io/javastack/2018/04/18/Spring Cloud/Spring Cloud是什么？/" data-id="cjg4zd8ox004ohg8a4bzokg20" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    

        </footer>
    </div>
    
</article>



    <article id="post-Spring Cloud/SpringCloud Eureka自我保护机制" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <h2 id="自我保护背景"><a href="#自我保护背景" class="headerlink" title="自我保护背景"></a>自我保护背景</h2><p>首先对Eureka注册中心需要了解的是Eureka各个节点都是平等的，没有ZK中角色的概念， 即使N-1个节点挂掉也不会影响其他节点的正常运行。</p>
<p>默认情况下，如果Eureka Server在一定时间内（默认90秒）没有接收到某个微服务实例的心跳，Eureka Server将会移除该实例。但是当网络分区故障发生时，微服务与Eureka Server之间无法正常通信，而微服务本身是正常运行的，此时不应该移除这个微服务，所以引入了自我保护机制。</p>
<h2 id="自我保护机制"><a href="#自我保护机制" class="headerlink" title="自我保护机制"></a>自我保护机制</h2><p>官方对于自我保护机制的定义：</p>
<blockquote>
<p><a href="https://github.com/Netflix/eureka/wiki/Understanding-Eureka-Peer-to-Peer-Communication" target="_blank" rel="noopener">https://github.com/Netflix/eureka/wiki/Understanding-Eureka-Peer-to-Peer-Communication</a></p>
</blockquote>
<p>自我保护模式正是一种针对网络异常波动的安全保护措施，使用自我保护模式能使Eureka集群更加的健壮、稳定的运行。</p>
<p>自我保护机制的工作机制是如果在15分钟内超过85%的客户端节点都没有正常的心跳，那么Eureka就认为客户端与注册中心出现了网络故障，Eureka Server自动进入自我保护机制，此时会出现以下几种情况：</p>
<p>1、Eureka Server不再从注册列表中移除因为长时间没收到心跳而应该过期的服务。\<br>2、Eureka Server仍然能够接受新服务的注册和查询请求，但是不会被同步到其它节点上，保证当前节点依然可用。\<br>3、当网络稳定时，当前Eureka Server新的注册信息会被同步到其它节点中。</p>
<p>因此Eureka Server可以很好的应对因网络故障导致部分节点失联的情况，而不会像ZK那样如果有一半不可用的情况会导致整个集群不可用而变成瘫痪。</p>
<h2 id="自我保护开关"><a href="#自我保护开关" class="headerlink" title="自我保护开关"></a>自我保护开关</h2><p>Eureka自我保护机制，通过配置<code>eureka.server.enable-self-preservation</code>来true打开/false禁用自我保护机制，默认打开状态，建议生产环境打开此配置。</p>
<h2 id="开发环境配置"><a href="#开发环境配置" class="headerlink" title="开发环境配置"></a>开发环境配置</h2><p>开发环境中如果要实现服务失效能自动移除，只需要修改以下配置。</p>
<h4 id="1、-注册中心关闭自我保护机制，修改检查失效服务的时间。"><a href="#1、-注册中心关闭自我保护机制，修改检查失效服务的时间。" class="headerlink" title="1、 注册中心关闭自我保护机制，修改检查失效服务的时间。"></a>1、 注册中心关闭自我保护机制，修改检查失效服务的时间。</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">eureka:</span><br><span class="line">  server: </span><br><span class="line">    enable-self-preservation: false</span><br><span class="line">    eviction-interval-timer-in-ms: 3000</span><br></pre></td></tr></table></figure>
<h4 id="2、-微服务修改减短服务心跳的时间。"><a href="#2、-微服务修改减短服务心跳的时间。" class="headerlink" title="2、 微服务修改减短服务心跳的时间。"></a>2、 微服务修改减短服务心跳的时间。</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"># 默认90秒</span><br><span class="line">lease-expiration-duration-in-seconds: 10</span><br><span class="line"># 默认30秒</span><br><span class="line">lease-renewal-interval-in-seconds: 3</span><br></pre></td></tr></table></figure>
<p>以上配置建议在生产环境使用默认的时间配置。</p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://youanyyou.gitee.io/javastack/2018/04/18/Spring Cloud/SpringCloud Eureka自我保护机制/" data-id="cjg4zd8p0004qhg8a6wjhs4xs" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    

        </footer>
    </div>
    
</article>



    <article id="post-Spring Cloud/SpringCloud配置中心内容加密" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>从配置获取的配置默认是明文的，有些像数据源这样的配置需要加密的话，需要对配置中心进行加密处理。</p>
<p>下面使用对称性加密来加密配置，需要配置一个密钥，当然也可以使用RSA非对称性加密，但对称加密比较方便也够用了，这里就以对称加密来配置即可。</p>
<h2 id="1、安装JCE"><a href="#1、安装JCE" class="headerlink" title="1、安装JCE"></a>1、安装JCE</h2><p>JDK下的JCR默认是有长度限制的，需要替换没有长度限制的JCE版本。</p>
<blockquote>
<p><a href="http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html" target="_blank" rel="noopener">http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html</a></p>
</blockquote>
<p>把下载包里面的两个jar文件复制替换到JAVA_HOME/jre/lib/security目录下。</p>
<h2 id="2、添加加密KEY"><a href="#2、添加加密KEY" class="headerlink" title="2、添加加密KEY"></a>2、添加加密KEY</h2><p>配置中心配置文件中加入加密密钥。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">encrypt: </span><br><span class="line">  key: 0e010e17-2529-4581-b907-c8edcfd6be09</span><br></pre></td></tr></table></figure>
<h2 id="3、查看加密功能状态"><a href="#3、查看加密功能状态" class="headerlink" title="3、查看加密功能状态"></a>3、查看加密功能状态</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://192.168.1.237:7100/encrypt/status</span><br></pre></td></tr></table></figure>
<p>功能正常会显示OK</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&quot;status&quot;:&quot;OK&quot;&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4、加密解密"><a href="#4、加密解密" class="headerlink" title="4、加密解密"></a>4、加密解密</h2><p>对<code>develop</code>字符串加密</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">curl http://192.168.1.237:7100/encrypt -d  develop -u config-user:99282424-5939-4b08-a40f-87b2cbc403f6</span><br></pre></td></tr></table></figure>
<p>对<code>develop</code>字符串解密</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">curl http://192.168.1.237:7100/decrypt -d  0fb593294187a31f35dea15e8bafaf77745328dcc20d6d6dd0dfa5ae753d6836 -u config-user:99282424-5939-4b08-a40f-87b2cbc403f6</span><br></pre></td></tr></table></figure>
<p>-u username:password 为basic认证</p>
<h2 id="5、配置文件"><a href="#5、配置文件" class="headerlink" title="5、配置文件"></a>5、配置文件</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">spring: </span><br><span class="line">  datasource: </span><br><span class="line">    username: &apos;&#123;cipher&#125;0fb593294187a31f35dea15e8bafaf77745328dcc20d6d6dd0dfa5ae753d6836&apos;</span><br></pre></td></tr></table></figure>
<p>需要加密的内容以<code>{cipher}</code>开头，并注意要使节单引号包起来，不然报错。</p>
<h2 id="6、读取配置"><a href="#6、读取配置" class="headerlink" title="6、读取配置"></a>6、读取配置</h2><p>这样客户端读取出来的配置是自动解密了的，如果要关闭自动解密功能通过客户端自己来解密，同时也要保留加解密的端点可以通过关闭以下配置即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">spring.cloud.config.server.encrypt.enabled=false</span><br></pre></td></tr></table></figure>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://youanyyou.gitee.io/javastack/2018/04/18/Spring Cloud/SpringCloud配置中心内容加密/" data-id="cjg4zd8p6004thg8ap55qxpms" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    

        </footer>
    </div>
    
</article>



    <article id="post-Spring Cloud/SpringCloud动态刷新配置信息" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>有时候在配置中心有些参数是需要修改的，这时候如何不重启而达到实时生效的效果呢？</p>
<h2 id="添加依赖"><a href="#添加依赖" class="headerlink" title="添加依赖"></a>添加依赖</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependencies&gt;</span><br><span class="line">    ...</span><br><span class="line">	&lt;dependency&gt;</span><br><span class="line">		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">		&lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;</span><br><span class="line">	&lt;/dependency&gt;	</span><br><span class="line">	...</span><br><span class="line">&lt;/dependencies&gt;</span><br></pre></td></tr></table></figure>
<p><code>spring-boot-starter-actuator</code>：这个模块的/refresh(POST请求)端点可以刷新配置，更多的使用参考Spring Boot系列文章。</p>
<h2 id="生效前提"><a href="#生效前提" class="headerlink" title="生效前提"></a>生效前提</h2><p>在需要刷新的Bean上添加@RefreshScope注解。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@RefreshScope</span><br><span class="line">@RestController</span><br><span class="line">public class TestController &#123;</span><br><span class="line"></span><br><span class="line">	@Value(&quot;$&#123;username&#125;&quot;)</span><br><span class="line">	private String username;</span><br><span class="line">	</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p>当配置更改时，标有@RefreshScope的Bean将得到特殊处理来生效配置。</p>
<h2 id="扩展问题"><a href="#扩展问题" class="headerlink" title="扩展问题"></a>扩展问题</h2><p>如果项目少配置少的情况可以通过/refresh来手动刷新配置，如果项目比较复杂的情况呢这种肯定是行不通的，Spring Cloud Bus消息总线可以解决配置修改的真正的动态刷新。</p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://youanyyou.gitee.io/javastack/2018/04/18/Spring Cloud/SpringCloud动态刷新配置信息/" data-id="cjg4zd8p1004rhg8ab5i82wqs" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    

        </footer>
    </div>
    
</article>



    <article id="post-Spring MVC/Spring MVC表单防重复提交" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>利用Spring MVC的过滤器及token传递验证来实现表单防重复提交。</p>
<h2 id="创建注解"><a href="#创建注解" class="headerlink" title="创建注解"></a>创建注解</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@Target(ElementType.METHOD)</span><br><span class="line">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="line">@Documented</span><br><span class="line">public @interface Token &#123;</span><br><span class="line"></span><br><span class="line">	boolean create() default false;</span><br><span class="line"></span><br><span class="line">	boolean remove() default false;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在跳转页面的方法上加上：@Token(create = true)\<br>在提交的action方法上加上：@Token(remove = true)</p>
<h2 id="创建过滤器"><a href="#创建过滤器" class="headerlink" title="创建过滤器"></a>创建过滤器</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line">public class TokenInterceptor extends HandlerInterceptorAdapter &#123;</span><br><span class="line"></span><br><span class="line">	private Logger logger = Logger.getLogger(TokenInterceptor.class);</span><br><span class="line"></span><br><span class="line">	private static final String TOKEN = &quot;token&quot;;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,</span><br><span class="line">			Object handler) throws Exception &#123;</span><br><span class="line">		if (handler instanceof HandlerMethod) &#123;</span><br><span class="line">			Method method = ((HandlerMethod) handler).getMethod();</span><br><span class="line">			Token annotation = method.getAnnotation(Token.class);</span><br><span class="line">			if (annotation != null) &#123;</span><br><span class="line">				HttpSession session = request.getSession();</span><br><span class="line"></span><br><span class="line">				// 创建token</span><br><span class="line">				boolean create = annotation.create();</span><br><span class="line">				if (create) &#123;</span><br><span class="line">					session.setAttribute(TOKEN, UUID.randomUUID().toString());</span><br><span class="line">					return true;</span><br><span class="line">				&#125;</span><br><span class="line"></span><br><span class="line">				// 删除token</span><br><span class="line">				boolean remove = annotation.remove();</span><br><span class="line">				if (remove) &#123;</span><br><span class="line">					if (isRepeatSubmit(request)) &#123;</span><br><span class="line">						logger.warn(&quot;表单不能重复提交:&quot; + request.getRequestURL());</span><br><span class="line">						return false;</span><br><span class="line">					&#125;</span><br><span class="line">					session.removeAttribute(TOKEN);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125; else &#123;</span><br><span class="line">			return super.preHandle(request, response, handler);</span><br><span class="line">		&#125;</span><br><span class="line">		return true;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	private boolean isRepeatSubmit(HttpServletRequest request) &#123;</span><br><span class="line">		String token = (String) request.getSession().getAttribute(TOKEN);</span><br><span class="line">		if (token == null) &#123;</span><br><span class="line">			return true;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		String reqToken = request.getParameter(TOKEN);</span><br><span class="line">		if (reqToken == null) &#123;</span><br><span class="line">			return true;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		if (!token.equals(reqToken)) &#123;</span><br><span class="line">			return true;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		return false;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="配置拦截器"><a href="#配置拦截器" class="headerlink" title="配置拦截器"></a>配置拦截器</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--配置拦截器 --&gt;  </span><br><span class="line">&lt;mvc:interceptors&gt; </span><br><span class="line">    &lt;mvc:interceptor&gt;  </span><br><span class="line">    	&lt;mvc:mapping path=&quot;/**&quot; /&gt; </span><br><span class="line">    	&lt;bean class=&quot;com.example.web.interceptor.TokenInterceptor&quot;/&gt;    </span><br><span class="line">    &lt;/mvc:interceptor&gt;</span><br><span class="line">&lt;/mvc:interceptors&gt;</span><br></pre></td></tr></table></figure>
<h2 id="表单添加token"><a href="#表单添加token" class="headerlink" title="表单添加token"></a>表单添加token</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type=&quot;hidden&quot; id=&quot;token&quot; name=&quot;token&quot; value=&quot;$!&#123;session.getAttribute(&apos;token&apos;)&#125;&quot;/&gt;</span><br></pre></td></tr></table></figure>
<p>在form表单里面添加token域，提交表单时需要传过去。</p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://youanyyou.gitee.io/javastack/2018/04/18/Spring MVC/Spring MVC表单防重复提交/" data-id="cjg4zd8pa004vhg8azxwszlrf" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    

        </footer>
    </div>
    
</article>



    <article id="post-Spring MVC/SpringMVC表单验证器" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>本章讲解SpringMVC中怎么通过注解对表单参数进行验证。</p>
<h2 id="SpringBoot配置"><a href="#SpringBoot配置" class="headerlink" title="SpringBoot配置"></a>SpringBoot配置</h2><p>使用springboot，<code>spring-boot-starter-web</code>会自动引入<code>hiberante-validator</code>,<code>validation-api</code>依赖。</p>
<p>在<code>WebMvcConfigurerAdapter</code>实现类里面添加验证器及国际化指定资源文件。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public Validator getValidator() &#123;</span><br><span class="line">	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();</span><br><span class="line">	validator.setValidationMessageSource(messageSource());</span><br><span class="line">	return validator;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@Bean</span><br><span class="line">public MessageSource messageSource() &#123;</span><br><span class="line">	ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();</span><br><span class="line">	messageSource.setBasename(&quot;i18n/ValidationMessages&quot;);</span><br><span class="line">	messageSource.setDefaultEncoding(StandardCharsets.US_ASCII.name());</span><br><span class="line">	return messageSource;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="验证器使用"><a href="#验证器使用" class="headerlink" title="验证器使用"></a>验证器使用</h2><p>接收参数的表单类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">public class LoginForm &#123;</span><br><span class="line"></span><br><span class="line">	@NotNull(message = &quot;&#123;login.loginName.length&#125;&quot;)</span><br><span class="line">	@Size(min = 4, max = 20, message = &quot;&#123;login.loginName.length&#125;&quot;)</span><br><span class="line">	private String loginName;</span><br><span class="line"></span><br><span class="line">	@NotNull(message = &quot;&#123;login.loginPassword.length&#125;&quot;)</span><br><span class="line">	@Size(min = 8, max = 20, message = &quot;&#123;login.loginPassword.length&#125;&quot;)</span><br><span class="line">	private String loginPassword;</span><br><span class="line"></span><br><span class="line">	public String getLoginName() &#123;</span><br><span class="line">		return loginName;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public void setLoginName(String loginName) &#123;</span><br><span class="line">		this.loginName = loginName;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public String getLoginPassword() &#123;</span><br><span class="line">		return loginPassword;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public void setLoginPassword(String loginPassword) &#123;</span><br><span class="line">		this.loginPassword = loginPassword;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在要验证的字段上面加入验证注解，更多参考<code>validation-api</code>jar包下的<code>javax.validation.constraints</code>包。</p>
<p>SpringMVC控制器：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@PostMapping(value = &quot;/login&quot;)</span><br><span class="line">public String login(@Validated LoginForm form) &#123;</span><br><span class="line">...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用<code>@Validated</code>注解表示该参数需要验证。</p>
<h2 id="国际化"><a href="#国际化" class="headerlink" title="国际化"></a>国际化</h2><p>message里面<code>{}</code>引用的是国际化的资源。</p>
<p>添加国际化资源文件：</p>
<p>ValidationMessages.properties<br>ValidationMessages_zh_CN.properties</p>
<p>需要指定编码为<code>ASCII</code>，不然会乱码。</p>
<h2 id="异常处理"><a href="#异常处理" class="headerlink" title="异常处理"></a>异常处理</h2><p>异常全局处理时进行处理：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">@ControllerAdvice</span><br><span class="line">public class ExceptionResolver &#123;</span><br><span class="line"></span><br><span class="line">	@ExceptionHandler(Throwable.class)</span><br><span class="line">	@ResponseBody</span><br><span class="line">	Object handleEntityException(HttpServletRequest request, Throwable ex) &#123;</span><br><span class="line">	    ...</span><br><span class="line">		if (ex instanceof BindException) &#123;</span><br><span class="line">			BindException c = (BindException) ex;</span><br><span class="line">			List&lt;ObjectError&gt; errors = c.getBindingResult().getAllErrors();</span><br><span class="line">			StringBuilder errorMsg = new StringBuilder();</span><br><span class="line">			errors.forEach(x -&gt; errorMsg.append(x.getDefaultMessage()).append(&quot;,&quot;));</span><br><span class="line">			</span><br><span class="line">		&#125;</span><br><span class="line">		...</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>或者在验证的类后面加<code>BindingResult</code>，错误信息都会放在该对象里面，而不会抛出异常。如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@PostMapping(value = &quot;/login&quot;)</span><br><span class="line">public String login(@Validated LoginForm form, BindingResult bindingResult) &#123;</span><br><span class="line">...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://youanyyou.gitee.io/javastack/2018/04/18/Spring MVC/SpringMVC表单验证器/" data-id="cjg4zd8pb004whg8ahyibdlqw" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    

        </footer>
    </div>
    
</article>



    <nav id="page-nav">
        <a class="extend prev" rel="prev" href="/javastack/page/2/">&laquo; 上一页</a><a class="page-number" href="/javastack/">1</a><a class="page-number" href="/javastack/page/2/">2</a><span class="page-number current">3</span><a class="page-number" href="/javastack/page/4/">4</a><a class="page-number" href="/javastack/page/5/">5</a><span class="space">&hellip;</span><a class="page-number" href="/javastack/page/12/">12</a><a class="extend next" rel="next" href="/javastack/page/4/">下一页 &raquo;</a>
    </nav>
</section>
            
                
<aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">分类</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Java/">Java</a><span class="category-list-count">37</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Java/多线程/">多线程</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Java/新特性/">新特性</a><span class="category-list-count">10</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Maven/">Maven</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Mybatis/">Mybatis</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Netty/">Netty</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/Tomcat/">Tomcat</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/书籍推荐/">书籍推荐</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/云计算/">云计算</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/开源项目/">开源项目</a><span class="category-list-count">10</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/测试/">测试</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/漏洞/">漏洞</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/程序人生/">程序人生</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/算法/">算法</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/编程语言/">编程语言</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/行业动态/">行业动态</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/javastack/categories/连接池/">连接池</a><span class="category-list-count">2</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">技术栈</h3>
        <div class="widget tagcloud">
            <a href="/javastack/tags/CAT/" style="font-size: 10px;">CAT</a> <a href="/javastack/tags/Cobar/" style="font-size: 10px;">Cobar</a> <a href="/javastack/tags/Cookie/" style="font-size: 10px;">Cookie</a> <a href="/javastack/tags/Disconf/" style="font-size: 10px;">Disconf</a> <a href="/javastack/tags/Druid/" style="font-size: 12.86px;">Druid</a> <a href="/javastack/tags/Eclipse/" style="font-size: 10px;">Eclipse</a> <a href="/javastack/tags/Facebook/" style="font-size: 10px;">Facebook</a> <a href="/javastack/tags/IP/" style="font-size: 10px;">IP</a> <a href="/javastack/tags/IaaS/" style="font-size: 10px;">IaaS</a> <a href="/javastack/tags/JVM/" style="font-size: 10px;">JVM</a> <a href="/javastack/tags/Java/" style="font-size: 20px;">Java</a> <a href="/javastack/tags/Jodd/" style="font-size: 10px;">Jodd</a> <a href="/javastack/tags/Junit/" style="font-size: 10px;">Junit</a> <a href="/javastack/tags/Kotlin/" style="font-size: 10px;">Kotlin</a> <a href="/javastack/tags/LVS/" style="font-size: 10px;">LVS</a> <a href="/javastack/tags/Maven/" style="font-size: 14.29px;">Maven</a> <a href="/javastack/tags/Mybatis/" style="font-size: 10px;">Mybatis</a> <a href="/javastack/tags/NIO/" style="font-size: 10px;">NIO</a> <a href="/javastack/tags/Netty/" style="font-size: 10px;">Netty</a> <a href="/javastack/tags/Nginx/" style="font-size: 10px;">Nginx</a> <a href="/javastack/tags/Oracle/" style="font-size: 11.43px;">Oracle</a> <a href="/javastack/tags/PaaS/" style="font-size: 10px;">PaaS</a> <a href="/javastack/tags/Python/" style="font-size: 10px;">Python</a> <a href="/javastack/tags/SaaS/" style="font-size: 10px;">SaaS</a> <a href="/javastack/tags/Squid/" style="font-size: 10px;">Squid</a> <a href="/javastack/tags/Tengine/" style="font-size: 10px;">Tengine</a> <a href="/javastack/tags/Thrift/" style="font-size: 10px;">Thrift</a> <a href="/javastack/tags/Tomcat/" style="font-size: 12.86px;">Tomcat</a> <a href="/javastack/tags/https/" style="font-size: 10px;">https</a> <a href="/javastack/tags/jdk10/" style="font-size: 10px;">jdk10</a> <a href="/javastack/tags/jdk7/" style="font-size: 10px;">jdk7</a> <a href="/javastack/tags/jdk8/" style="font-size: 17.14px;">jdk8</a> <a href="/javastack/tags/jdk9/" style="font-size: 10px;">jdk9</a> <a href="/javastack/tags/书籍/" style="font-size: 15.71px;">书籍</a> <a href="/javastack/tags/云计算/" style="font-size: 10px;">云计算</a> <a href="/javastack/tags/代理/" style="font-size: 10px;">代理</a> <a href="/javastack/tags/分布式/" style="font-size: 11.43px;">分布式</a> <a href="/javastack/tags/区块链/" style="font-size: 10px;">区块链</a> <a href="/javastack/tags/多线程/" style="font-size: 12.86px;">多线程</a> <a href="/javastack/tags/安全/" style="font-size: 10px;">安全</a> <a href="/javastack/tags/开源项目/" style="font-size: 18.57px;">开源项目</a> <a href="/javastack/tags/性能优化/" style="font-size: 10px;">性能优化</a> <a href="/javastack/tags/攻击/" style="font-size: 10px;">攻击</a> <a href="/javastack/tags/数据库/" style="font-size: 10px;">数据库</a> <a href="/javastack/tags/架构师/" style="font-size: 11.43px;">架构师</a> <a href="/javastack/tags/测试/" style="font-size: 10px;">测试</a> <a href="/javastack/tags/漏洞/" style="font-size: 11.43px;">漏洞</a> <a href="/javastack/tags/监控/" style="font-size: 11.43px;">监控</a> <a href="/javastack/tags/程序人生/" style="font-size: 12.86px;">程序人生</a> <a href="/javastack/tags/算法/" style="font-size: 11.43px;">算法</a> <a href="/javastack/tags/缓存/" style="font-size: 10px;">缓存</a> <a href="/javastack/tags/编程语言/" style="font-size: 10px;">编程语言</a> <a href="/javastack/tags/腾讯/" style="font-size: 10px;">腾讯</a> <a href="/javastack/tags/行业动态/" style="font-size: 10px;">行业动态</a> <a href="/javastack/tags/负载均衡/" style="font-size: 11.43px;">负载均衡</a> <a href="/javastack/tags/连接池/" style="font-size: 12.86px;">连接池</a> <a href="/javastack/tags/阿里巴巴/" style="font-size: 14.29px;">阿里巴巴</a> <a href="/javastack/tags/高并发/" style="font-size: 10px;">高并发</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title">链接</h3>
        <div class="widget">
            <ul>
                
                    <li>
                        <a href="http://hexo.io">Hexo</a>
                    </li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>

            
        </div>
        <footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            &copy; 2018 Java技术栈 版权所有
            <br>
            Powered by <a href="http://www.javastack.cn/" target="_self">javastack.cn</a>. 
        </div>
    </div>
</footer>
        


    
        <script src="/javastack/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/javastack/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/javastack/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="/javastack/js/main.js"></script>

    </div>
</body>
</html>